package com.wedo.mall;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.multidex.MultiDexApplication;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.e.library.entity.User;
import com.e.library.http.EClient;
import com.e.library.utils.ESPUtils;
import com.e.library.utils.EStack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.model.EaseNotifier;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.util.EasyUtils;
import com.mob.MobSDK;
import com.tencent.bugly.crashreport.CrashReport;
import com.wedo.mall.activity.LoginActivity;
import com.wedo.mall.activity.chat.ConsultActivity;
import com.wedo.mall.activity.goods.GoodsDetailActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.activity.user.MessageDetailActivity;
import com.wedo.mall.activity.user.OrderDetailActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lxy on 2017/6/8.
 */

public class WApp extends MultiDexApplication {

    private static Context context;
    @Override
    public void onCreate() {
        super.onCreate();

        Log.i("WApp","WApp onCreate");

        context = this;
        EClient.with().init(this);
        ease();
        MobSDK.init(context,"1ff6ac94abe04","faa46d6b058066c6fac9dfc2d73d9020");
        CrashReport.initCrashReport(this,"1ddcd9dea5",BuildConfig.DEBUG);
    }

    public static Context app(){
        return context;
    }

    /**定位成功，保存经纬度*/
    public static void onLocationSuccessful(double lng,double lat){
        ESPUtils.setString(context,"latitude",String.valueOf(lat));
        ESPUtils.setString(context,"longitude",String.valueOf(lng));
    }

    public static String lat(){
        return ESPUtils.getString(context,"latitude","5.24");
    }

    public static String lng(){
        return ESPUtils.getString(context,"longitude","100.14");
    }

    public static Map<String,String> lngLat(){
        Map<String,String> map = new HashMap<>(2);
        map.put("latitude",lat());
        map.put("longitude",lng());
        return map;
    }

    private void ease(){

        EaseUI.getInstance().init(this, null);
        setConnectionListener();
        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                if (EStack.isEmpty()){
                    EaseUI.getInstance().getNotifier().onNewMesg(list);
                }else {
                    String activity = EasyUtils.getTopActivityName(context);
                    if (!TextUtils.equals("ConsultActivity",activity)){
                        EaseUI.getInstance().getNotifier().onNewMesg(list);
                    }
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageRead(List<EMMessage> list) {
            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {
            }

            @Override
            public void onMessageRecalled(List<EMMessage> list) {
            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {
            }
        });

        EaseUI.getInstance().getNotifier().setNotificationInfoProvider(new EaseNotifier.EaseNotificationInfoProvider() {
            @Override
            public String getDisplayedText(EMMessage message) {
//                String body = EaseCommonUtils.txtBody(message);
                String body = EaseCommonUtils.getMessageDigest(message,context);
                return body;
            }

            @Override
            public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
//                String body = EaseCommonUtils.txtBody(message);
                String body = EaseCommonUtils.getMessageDigest(message,context);
                return body;
            }

            @Override
            public String getTitle(EMMessage message) {
                int type = EaseCommonUtils.type(message);
                if (type == EaseConstant.TYPE_ORDER){
                    return getResources().getString(R.string.user_ordermessage);
                }else if (type == EaseConstant.TYPE_SYSTEM || type == EaseConstant.TYPE_GOODS){
                    return getResources().getString(R.string.user_systemmessage);
                }

                User user = EaseCommonUtils.user(message);
                if (user !=null){
                    return user.nickname;
                }
                return message.getUserName();
            }

            @Override
            public int getSmallIcon(EMMessage message) {
                return 0;
            }

            @Override
            public Intent getLaunchIntent(EMMessage message) {
                Map<String,Object> map = message.ext();
                if(map !=null) {
                    Log.i("ease_ext",map.toString());
                }

                int type = EaseCommonUtils.type(message);
                if (type == EaseConstant.TYPE_ORDER){
                    String order_sn = message.getStringAttribute("order_sn","");
                    if (TextUtils.isEmpty(order_sn)){
                        return null;
                    }

                    Intent intent = new Intent(getApplicationContext(), OrderDetailActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(OrderDetailActivity.EXTRA_ORDER_SN,order_sn);
                    return intent;
                }else if (type == EaseConstant.TYPE_SYSTEM){
                    String id = message.getStringAttribute("id","");
                    if (TextUtils.isEmpty(id)){
                        return null;
                    }

                    /**test*/
//                    if(BuildConfig.DEBUG) {
//                        id = "176";
//                    }

                    Intent intent = new Intent(getApplicationContext(), MessageDetailActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(MessageDetailActivity.MESSAGE_ID,id);
                    return intent;
                }else if (type == EaseConstant.TYPE_GOODS){
                    String id = message.getStringAttribute("id","");
                    if (TextUtils.isEmpty(id)){
                        return null;
                    }

                    Intent intent = new Intent(getApplicationContext(), GoodsDetailActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(GoodsDetailActivity.EXTRA_GOODS_ID,id);
                    return intent;
                }

                User user = EaseCommonUtils.user(message);
                if (user == null){
                    Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                    return intent;
                }

                Intent intent = new Intent(getApplicationContext(), ConsultActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                String id = user.id;
                if (!id.startsWith("wedo")){
                    id = "wedo"+user.id;
                }

                Bundle bundle = new Bundle();
                bundle.putParcelable("receiver",user);
                bundle.putString(EaseConstant.EXTRA_PHONE,"");
                bundle.putString(EaseConstant.EXTRA_USER_ID,id);
                bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE,EaseConstant.CHATTYPE_SINGLE);
                intent.putExtras(bundle);
                return intent;
            }
        });
    }

    private void setConnectionListener(){
        EMConnectionListener listener = new EMConnectionListener() {
            @Override
            public void onConnected() {

            }

            @Override
            public void onDisconnected(int error) {
                if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    onConnectionConflict();
                }
            }
        };

        EMClient.getInstance().addConnectionListener(listener);
    }

    private void onConnectionConflict(){
        WLogin.logout(this);
        if (!EasyUtils.isAppRunningForeground(this)){
            showConflictNotifier();
        }else {
            gotoLoginActivity();
        }
    }

    private void showConflictNotifier() {

        Intent intent = new Intent(this,LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        NotificationManager mNotificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.wedo_logo)
                .setContentTitle(getResources().getString(R.string.login_conflict_tips))
                .setContentText(getResources().getString(R.string.login_conflict_txt));
        mBuilder.setTicker(getResources().getString(R.string.login_conflict_ticker));
        mBuilder.setAutoCancel(true);
        PendingIntent pi= PendingIntent.getActivity(this, 1001, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pi);
        mNotificationManager.notify(1001, mBuilder.build());
    }

    private void gotoLoginActivity(){
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("Conflict", true);
        this.startActivity(intent);
    }

}
